<template>
  <!-- 我的标签 -->
  <div>
    <!-- 头部按钮 -->
    <NavigationComponent :isShowAdd="Boolean(false)" :breadList="breadList" @breadRouterClick="breadRouterClick">
      <div class="create_box" v-if="!hadFirst">
        <el-button type="primary" @click="getReNameOrAddTag('创建标签')">
          <i class="el-icon-plus"></i>
          <span class="create_text">创建标签</span>
        </el-button>
      </div>
    </NavigationComponent>

    <!-- 搜索 -->
    <searchInput @sortListClick="getSortListClick" :isHaveType="hadFirst ? 'onlyTime' : 'no'" :showPage="showPage">
      <template v-slot:search>
        <!-- 搜索 -->
        <el-input placeholder="搜索标签" prefix-icon="el-icon-search" v-model="searchValue" class="inputClass"
          @keyup.enter.native="getSearch">
        </el-input>
      </template>
    </searchInput>

    <div id="table_box" class="table_box">
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
        :row-style="{ height: '52px' }" :header-row-style="{ height: '52px' }" @selection-change="getSelectionChange"
        @row-dblclick="getFirstRowDblclick">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="名称" prop="labelName" show-overflow-tooltip
          :sortable="tableDataSelection.length == 0 && !hadFirst" min-width="200">
          <template v-slot:header="scope">
            <span v-if="tableDataSelection.length == 0">名称</span>
            <div v-else class="btn-header">
              <div class="btn-box" @click="getReNameOrAddTag('重命名')" v-if="tableDataSelection.length == 1 && !hadFirst">
                <el-icon class="btn-icon">
                  <Key />
                </el-icon>
                重命名
              </div>
              <div class="btn-box" @click="getDelete">
                <el-icon class="btn-icon">
                  <Delete />
                </el-icon>
                删除
              </div>
            </div>
          </template>

          <template #default="name">
            <div v-if="!hadFirst">
              <svg-icon icon-class="_biaoqian-" style="font-size: 22px; vertical-align: middle; margin-right: 6px" />
              {{ name.row.labelName }}
            </div>
            <div v-else>
              <svg-icon :icon-class="selectSvgIcons(name.row)"
                style="font-size: 22px; vertical-align: middle; margin-right: 6px" />
              {{ `${name.row.realName}${name.row.suffix ? '.' : ''}${name.row.suffix || ''} ` }}
            </div>
          </template>
        </el-table-column>

        <el-table-column v-if="hadFirst" label="文件来源">
          <template v-slot:header="scope">
            <span v-if="tableDataSelection.length == 0">文件来源</span>
            <span v-else>-</span>
          </template>

          <template #default="scope">
            <!-- <span v-if="scope.row.libraryType == 'personal'">个人文档</span> -->
            <span>团队文档</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" min-width="100" show-overflow-tooltip
          :sortable="tableDataSelection.length == 0">
          <template v-slot:header="scope">
            <span v-if="tableDataSelection.length == 0">创建时间</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <!-- 标签分页 -->
      <el-pagination v-if="!showPage" v-model:current-page="commonParams.page" v-model:page-size="commonParams.size"
        :page-sizes="[10, 20, 30, 40]" :disabled="disabled" :background="background"
        layout="total, prev, pager, next, sizes" :total="commonParams.total" @size-change="getSizeChange"
        @current-change="getPageChange" />

      <!-- 文件分页 -->
      <el-pagination v-if="showPage" v-model:current-page="requestStr.page" v-model:page-size="requestStr.size"
        :page-sizes="[10, 20, 30, 40]" :disabled="disabled" :background="background"
        layout="total, prev, pager, next, sizes" :total="requestStr.total" @size-change="FilegetSizeChange"
        @current-change="FilegetPageChange" />
    </div>

    <!-- 创建和重命名标签dialog -->
    <el-dialog :title="title" v-model="tagDialog" width="30%" @close="cancelTagDialog">
      <div class="tag-name">名称：<el-input style="width: 85%" v-model="tagName" placeholder="请输入内容"></el-input></div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelTagDialog">取 消</el-button>
          <el-button type="primary" @click="getConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import NavigationComponent from '@/views/personDoc/personal-component/tag-navg.vue' // 导航信息
import SearchInput from './components/search-input.vue' //搜索
import {
  ApiPerfilesUserLabel,
  ApiPerLabelCreate,
  ApiPerLabelupdate,
  apiFilesUserLabelDel,
  apiFilesLabelRecordDelete,
  ApiPerfilesLabelRecord,
  ApiPerGetParentTreeNodeAll
} from '@/api/teamKnowdge/teamTagsApi'

const background = ref(false)
const disabled = ref(false)
const { proxy } = getCurrentInstance() as any
const breadList = ref([]) as any
const title = ref('')
const tagDialog = ref(false)
const tagName = ref('')
const tableData = ref([])
const tableDataSelection = ref([])
const route = useRoute()
const commonParams = reactive({
  page: 1,
  size: 10,
  total: 0,
  sort: { sortDesc: 'create_time' }
})

const showPage = ref(false)
const hadFirst = ref(false)
const labelId = ref(null)
const searchValue = ref('')
const loading = ref(false)
const fileTypeList = reactive({
  personal: 0,
  team: 1,
  enterprise: 2
})
const requestStr = reactive({
  page: 1,
  size: 10,
  total: 0,
  sort: { sortDesc: 'create_time' }
})
// 获取标签data
const getTableData = async (reset) => {
  loading.value = true
  if (reset == 'reset') {
    commonParams.page = 1
    commonParams.size = 10
    tableData.value = []
  }
  let param = {
    size: commonParams.size,
    page: commonParams.page - 1,
    labelName: searchValue.value || null,
    teamId: route.query.teamId
  }

  let oParam = { ...param, ...commonParams.sort }
  ApiPerfilesUserLabel(oParam)
    .then((res) => {
      tableData.value = res.data.rows
      commonParams.total = res.data.total
      breadList.value = [
        {
          label: '所有标签',
          id: ''
        }
      ]
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 创建标签或重命名
const getReNameOrAddTag = (e) => {
  // console.log(e, '创建标签或重命名');

  title.value = e
  tagDialog.value = true

  if (e == '重命名') {
    tagName.value = tableDataSelection.value[0].labelName
  }
}

// 关闭标签 创建或者修改
const cancelTagDialog = () => {
  tagName.value = ''
  tagDialog.value = false
}

// 确定
const getConfirm = async () => {
  if (!tagName.value) {
    ElMessage.warning('标签名不能为空')
    return
  }
  let id = tableDataSelection.value.map((item) => item.id)
  let params = {
    labelName: tagName.value,
    teamId: route.query.teamId,
  }
  let fn = title.value == '创建标签'
  if (fn) {
    await ApiPerLabelCreate(params)
  } else {
    await ApiPerLabelupdate(params)
  }
  ElMessage({
    type: 'success',
    message: fn ? '创建成功!' : '重命名成功!'
  })
  getTableData('reset')
  cancelTagDialog()
}

// 搜索文件名
const getSearch = () => {
  console.log(searchValue.value)
  // getTableData('reset');
  hadFirst.value ? getFilesLabelData('reset') : getTableData('reset')
}

// 删除
const getDelete = () => {
  let ids = tableDataSelection.value.map((item) => item.id)

  if (hadFirst.value) {
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        // 进入标签下文件的删除
        let params = {
          fileType: 'team',
          ids: ids,
          labelId: labelId.value,
          labelType: 'team'
        }
        await apiFilesLabelRecordDelete(params)
        ElMessage.success('删除成功！')
        getChangeData()
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  } else {
    // 删除标签
    ElMessageBox.confirm('此操作将永久删除该标签, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        // 第一层 (判断是否有文件存在标签下)
        let params = {
          is: false,
          labelId: ids,
          teamId: route.query.teamId
        }
        const res = await apiFilesUserLabelDel(params)
        // 返回 415 标签下还有文件
        if (res.code == 415) {
          ElMessageBox.confirm('当前标签已使用，是否确认删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              let params = {
                is: true,
                labelId: ids
              }
              await apiFilesUserLabelDel(params)
              ElMessage.success('删除成功！')
              getChangeData()
            })
            .catch(() => {
              ElMessage.info('已取消删除')
            })
        } else {
          ElMessage.success('删除成功！')
          getChangeData()
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }
}

const breadRouterClick = (val) => {
  if (!val.id) {
    loading.value = true
    getTableData('reset')
    hadFirst.value = false
  }
  searchValue.value = ''
  showPage.value = false
}

// 排序
const getSortListClick = (item) => {
  if (item.valueIndex == 0) {
    commonParams.sort = { sortDesc: 'create_time' }
  } else {
    // 双击进去 名称  排序的字段不一样 （外面是标签排序，里面是文件排序）
    commonParams.sort = { ...item.value[item.valueIndex - 1] }
  }
  getTableData(null)
}

const getSizeChange = (val) => {
  commonParams.size = val
  getTableData(null)
}

const getPageChange = (val) => {
  commonParams.page = val
  getTableData(null)
}

// 如果 hadFirst 为true,获取双击后的数据 ，false则第一次的数据
const getChangeData = () => {
  if (hadFirst.value) {
    getFilesLabelData('')
  } else {
    getTableData('')
  }
}

// 双击表格行进入下一级 (第一次双击table行)
const getFirstRowDblclick = (row) => {
  searchValue.value = ''
  labelId.value = row.id
  if (!hadFirst.value) {
    hadFirst.value = true
    loading.value = true
    breadList.value.push({
      label: row.labelName,
      id: row.id
    })
    // 排序默认初始值
    requestStr.sort = { sortDesc: 'create_time' }
    showPage.value = true
    getFilesLabelData('reset')
  } else {
    // 原本页面跳转方法
    handleRowDblClick(row)
  }
}

// 第一次双击table行获取数据
const getFilesLabelData = async (reset) => {
  if (reset == 'reset') {
    tableData.value = []
    requestStr.page = 1
    requestStr.size = 10
  }
  let param = {
    size: requestStr.size,
    page: requestStr.page - 1,
    fileType: 'team',
    labelId: labelId.value,
    labelName: searchValue.value,
    labelType: 'team',
    teamId: route.query.teamId
  }

  let params = { ...param, ...requestStr.sort }
  const res = await ApiPerfilesLabelRecord(params)
  if (res.data) {
    tableData.value = res.data.rows
    requestStr.total = res.data.total
  }

  loading.value = false
}

const FilegetSizeChange = (val) => {
  requestStr.size = val
  getFilesLabelData(null)
}

const FilegetPageChange = (val) => {
  requestStr.page = val
  getFilesLabelData(null)
}

// table 选择状态
const getSelectionChange = (val) => {
  tableDataSelection.value = val
}

// icon替换
const selectSvgIcons = (v) => {
  return proxy.$yuUtils.selectSvgIcon(v)
}

// 原页面保留 双击跳转
const handleRowDblClick = (row) => {
  row.libraryType = 'team'
  if (row.libraryType) {
    //双击调整转到指定页面
    let params = {
      id: row.id,
      fileType: 1
    }

    ApiPerGetParentTreeNodeAll(params).then((res) => {
      let expandedKeys = res.data.map((item) => {
        let obj = {
          id: parseInt(item.id),
          label: item.realName
        }
        return obj
      })
      showPage.value = false
      sessionStorage.setItem('expandedKeys', JSON.stringify(expandedKeys))
      proxy.$router.push({ path: '/newUi/teamKnowdge/teamFile', query: { headNodeId: expandedKeys[0].id, teamId: row.teamId } })
    })
  }

  // else {
  //   requestStr.value.page = 1;
  //   requestStr.value.size = 10;
  //   apiFilesLabelRecordQuery(row);
  // }
}

onMounted(() => {
  getTableData('reset')
})
</script>

<style scoped lang="scss">
.tag-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

#table_box {
  overflow: auto;
  height: calc(100vh - 210px);
}

.table_box {
  margin-left: 20px;

  .btn-header {
    height: 32px;
    display: flex;
    align-items: center;
    padding: 0px;

    .btn-box {
      display: flex !important;
      align-items: center !important;
      color: #666;
      font-size: 14px;
      margin-right: 20px;
      cursor: pointer;
      white-space: nowrap;
      font-weight: 400;
      padding: 0px;

      .btn-icon {
        margin-right: 6px;
        color: #999;
        font-size: 15px;
      }

      .svg-icon {
        width: 15px;
        height: 15px;
        margin-right: 6px;
      }
    }

    .btn-box:hover {
      color: rgb(102, 152, 255);
    }

    .btn-box:hover .svg-icon {
      color: rgb(102, 152, 255);
    }

    .btn-box:hover .btn-icon {
      color: rgb(102, 152, 255);
    }
  }
}

.el-pagination {
  // margin-top: 25px;
  padding: 0px 16px;
}

.header-title {
  font-weight: 700px;
}
</style>
